//
//  MCScanViewController.swift
//  WisdomSpace
//
//  Created by MC on 2017/11/21.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit
import AVFoundation

protocol MCScanViewControllerDelegate : NSObjectProtocol {
    func MCScanViewController_getResult(str:String)
}


enum MCScanType {
    case orderScan          // 订单扫描
    case sweepPayScan       // 优惠买单扫描
    case checkOrderScan     // 核销单扫描
    case otherScan          // 其他扫描  只需要返回扫描结果
}


class MCScanViewController: MCViewController,AVCaptureMetadataOutputObjectsDelegate {
    
    public var payMoney = 0.0       // 扫码收款的金额

    
  
    
    public var scanType : MCScanType = MCScanType.orderScan
    
    
    
    weak var customDelegate : MCScanViewControllerDelegate?
    var device:AVCaptureDevice!
    var input:AVCaptureDeviceInput!
    var output:AVCaptureMetadataOutput!
    var session:AVCaptureSession!
    var preview:AVCaptureVideoPreviewLayer!
    
    
    //相机显示视图
    let cameraView = MCScanView(frame: UIScreen.main.bounds)
    
    let captureSession = AVCaptureSession()
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "扫一扫"
        self.view.backgroundColor = UIColor.black
        self.view.addSubview(cameraView)
        
        
        
        
        view.addSubview(backButton)
        backButton.snp.remakeConstraints { (make) -> Void in
            make.left.equalTo(view).offset(10)
            make.top.equalTo(view).offset(MCStatusBarHeight)
            make.size.equalTo(CGSize.init(width: 40, height: 44))
        }
        
                
        view.addSubview(titleLabel)
        titleLabel.snp.remakeConstraints { (make) -> Void in
            make.centerX.equalTo(view)
            make.top.equalTo(view).offset(MCStatusBarHeight)
            make.height.equalTo(MCNavigationBarHeight(self))
        }
        
        
        do{
            self.device = AVCaptureDevice.default(for: AVMediaType.video)
            
            if device == nil {
                return
            }
            
            self.input = try AVCaptureDeviceInput(device: device)
            
            self.output = AVCaptureMetadataOutput()
            output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
            
            self.session = AVCaptureSession()
            if UIScreen.main.bounds.size.height<500 {
                self.session.sessionPreset = AVCaptureSession.Preset.vga640x480
            }else{
                self.session.sessionPreset = AVCaptureSession.Preset.high
            }
            
            self.session.addInput(self.input)
            self.session.addOutput(self.output)
            
            self.output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr,AVMetadataObject.ObjectType.ean13,AVMetadataObject.ObjectType.ean8,AVMetadataObject.ObjectType.code128]
            
            //设置可探测区域
            output.rectOfInterest = CGRect(x: 0.2, y: 0.2, width: 0.6, height: 0.6)

            self.preview = AVCaptureVideoPreviewLayer(session:self.session)
            self.preview.videoGravity = AVLayerVideoGravity.resizeAspectFill
            self.preview.frame = UIScreen.main.bounds
            self.view.layer.insertSublayer(self.preview, at:0)
            
            
            //开始捕获
            self.session.startRunning()
        }catch _ {
            //打印错误消息
            let alertController = UIAlertController(title: "提醒",
                                                    message: "请在iPhone的\"设置-隐私-相机\"选项中,允许本程序访问您的相机",
                                                    preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        self.scannerStart()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    
    @objc func backButtonClicked() {
        self.navigationController?.popViewController(animated: true)
    }
    
    func scannerStart(){
        captureSession.startRunning()
        cameraView.scanning = "start"
    }
    
    func scannerStop() {
        captureSession.stopRunning()
        cameraView.scanning = "stop"
    }
    
    
    func metadataOutput(_ output: AVCaptureMetadataOutput,
                        didOutput metadataObjects: [AVMetadataObject],
                        from connection: AVCaptureConnection) {
        var stringValue:String?
        if metadataObjects.count > 0 {
            let metadataObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
            stringValue = metadataObject.stringValue
            if stringValue != nil{
                self.session.stopRunning()
            }
        }
        self.session.stopRunning()
        scannerStop()
        //输出结果

        
        switch scanType {
        case MCScanType.checkOrderScan:
            print("核销的的扫描结果")
            self.orderResult(stringValue: stringValue!)
        case MCScanType.sweepPayScan:
            self.sweepPay(stringValue: stringValue!)
        case MCScanType.orderScan:
            self.orderResult(stringValue: stringValue!)
        default:
            self.navigationController?.popViewController(animated: true)
            self.customDelegate?.MCScanViewController_getResult(str: stringValue!)
            break
        }
    }
    
    
    
    func orderResult(stringValue:String) {
        let para = [
            "expressNo" : stringValue,
            "storeId"     : MCUserinfo_getStoreId()
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_updateOrderInfoStatus, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            
            let dataDict = response["data"] as! [String : AnyObject]
            let status = dataDict["status"] as! NSNumber
            let orderSn = dataDict["orderSn"] as! String
            
            
            MCAlterController_twoOptions(vc: self, message: "发货成功，是否查看该订单详情？", confirm: {
                switch status.intValue {
                case 2:
                    let vc = MCOrderDetailWaitSendViewController()
                    vc.orderSn = orderSn
                    MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
                    break
                case 3:
                    let vc = MCOrderDetailWaitPickUpViewController()
                    vc.orderSn = orderSn
                    MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
                    break
                case 4:
                    let vc = MCOrderDetailCompleteViewController()
                    vc.orderSn = orderSn
                    MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
                    break
                case 6:
                    let vc = MCOrderDetailSuccessfulDealViewController()
                    vc.orderSn = orderSn
                    MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
                    break
                default:
                    break
                }
                
            }, cancle: {})
            
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    func sweepPay(stringValue:String) {
        
        let identifierNumber = UIDevice.current.identifierForVendor?.uuidString
                
        let number = identifierNumber?.replacingOccurrences(of: "-", with: "")
        
        
        let para = [
            "authorCode" : stringValue,
            "machineNo"  : number ?? "",
            "terminalType" : 3,
            "totalPrice" : payMoney,
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_microPay, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in
            let dataDict = response["data"] as? [String : AnyObject] ?? [:]
            
            let vc = MCSweepPayResultViewController()
            vc.dataDict = dataDict as NSDictionary
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)

            
        }, dislike: { (response) in }) { (error) in }
    }
    
    lazy var backButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.setImage(#imageLiteral(resourceName: "Reuse_back_white"), for: UIControlState.normal)
        button.addTarget(self, action: #selector(backButtonClicked), for: UIControlEvents.touchUpInside)
        return button
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = MCFont(21)
        label.textColor = UIColor.white
        label.textAlignment = NSTextAlignment.center
        label.text = "扫一扫"
        return label
    }()
}

